// 引入接口文件
import { findByCity, getProjectPermission, addFun, queryInfo, findCometingGoods, getPriceRatio, changeStatus } from './weekReportDetailServ.js'

// 对象和JSON字符串互转
import { parse } from 'qs'
// 弹出消息框
import { message } from 'antd'
// 日期处理对象
import moment from 'moment'
import { rstr2b64 } from '../../../../utils/md5'
/* isEmpty 对象是否为空
 * isArray 对象是否数组
 * cloneDeep 对象深拷贝
 */
import { isEmpty, isArray, cloneDeep, merge } from 'lodash'
// 引入路由对象
import { hashHistory } from 'dva/router'

// 初始默认状态
const defultState = {
  btnLoading: false,
  tableData: [],
  loading: false,
  actionType: 'add',
  areaList: [],
  products: [],
  cityList: [],
  query: {
    "project": "",
    "endTime": "",
    "beginTime": "",
    "area": "",
    "city": "",
    "cityid": "",
    "areaid": "",
    "projectid": "",
    "WeeklyCompet": [],
  }
}

// 声明module
const tmpModule = {
  namespace: 'defaultModel',
  // 默认状态
  state: cloneDeep(defultState),
  // 入口函数(先执行)
  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname, query }) => {
        // 页面路由匹配时执行
        if ('' + tmpModule.pathname === '' + pathname) {
          // 执行业务操作
          dispatch({ type: 'updateStore', payload: { ...cloneDeep(defultState), ...query } })//每次进去页面先重置状态
          // if(query.actionType == 'check'|| query.actionType == 'edit'){
          //   dispatch({type: 'queryInfo',payload: {id:query.id}})
          // }
          dispatch({ type: 'getProjectPermission', payload: { id: query.id } })
        } // end if
      }) // end listen
    },
  },

  // 方法列表
  effects: {
    // 查询记录
    *queryInfo({ payload }, { put, select, call }) {
      let { query } = yield select(state => state[tmpModule.namespace])
      let params = {
        id: payload.id,
      }
      const { success, result } = yield call(queryInfo, { ...params })
      if (success) {
        query = result
        yield put({ type: 'updateStore', payload: { query } })
        yield put({ type: 'findByCity', payload: { areaId: query.areaid } })
      }
    },
    *getPriceRatio({ payload }, { put, select, call }) {
      let { query } = yield select(state => state[tmpModule.namespace])
      let params = {
        begintime: query.beginTime,
        endtime: query.endTime,
        projectId: query.projectid,
        productType: payload.iit.productType,
        ro: payload.iit.averagePrice,
        competid: payload.iit.competId,
        houseStaus: payload.iit.houseStatus,
      }
      const { success, result } = yield call(getPriceRatio, { ...params })
      if (success) {
        for (var it of query.WeeklyCompet) {
          for (var po of it.competitorInformation) {
            if (payload.iit.id == po.id) {
              po.priceRatio = result
            }
          }
        }
        yield put({
          type: 'updateStore',
          payload: { query }
        })
      }
    },
    *getProjectPermission({ payload }, { put, select, call }) {
      let { areaList, actionType } = yield select(state => state[tmpModule.namespace])
      let params = {
        userId: localStorage.username
      }
      const { success, projectCityList } = yield call(getProjectPermission, { ...params })
      if (success) {
        areaList = projectCityList.map((item, index) => {
          return {
            label: item.areaName,
            value: item.areaId,
            children: item.cityList
          }
        })
        yield put({
          type: 'updateStore',
          payload: { areaList }
        })
        if (actionType == 'check' || actionType == 'edit') {
          yield put({ type: 'queryInfo', payload: { id: payload.id } })
        }
      }
    },
    // 查询竞品信息
    *findCometingGoods({ payload }, { put, select, call }) {
      let { query } = yield select(state => state[tmpModule.namespace])
      let params = {
        project: payload.projectId,
      }
      const { success, result } = yield call(findCometingGoods, { ...params })
      if (success) {
        query.WeeklyCompet = result
        yield put({
          type: 'updateStore',
          payload: { query }
        })
      }
    },
    *findByProject({ payload }, { put, select, call }) {
      let { products, cityList } = yield select(state => state[tmpModule.namespace])
      cityList.map((item, index) => {
        if (item.value == payload.cityid) {
          item.projectList.map((ele) => {
            ele.label = ele.projectName;
            ele.value = ele.projectId;
          });
          console.log(item, 'aaaa')
          products = item.projectList;
        }
      });
      yield put({ type: 'updateStore', payload: { products } })
    },
    *findByCity({ payload }, { put, select, call }) {
      let { cityList,query,actionType } = yield select(state => state[tmpModule.namespace])
      let params = {
        area: payload.areaId,
      }
      const { success, result } = yield call(findByCity, { ...params })
      if (success) {
        let list = result.filter(item => !!item)
        cityList = list.map((item, index) => {
          return {
            label: item.city,
            value: item.cityid,
            projectList: item.projectList
          }
        })
        yield put({
          type: 'updateStore',
          payload: { cityList }
        })
        if (actionType == 'check' || actionType == 'edit') {
          yield put({ type: 'findByProject', payload: { cityid: query.cityid } })
        }
      }
    },
    *submit({ payload }, { put, select, call }) {
      let { btnLoading, areaList, query, cityList, products, actionType } = yield select(state => state[tmpModule.namespace])
      query.area = areaList.filter(item => item.value == query.areaid)[0].label
      query.city = cityList.filter(item => item.value == query.cityid)[0].label
      query.project = products.filter(item => item.value == query.projectid)[0].label
      if (!query.WeeklyCompet.length) {
        message.warning('请先新增竞品信息')
        return
      }
      for (var it of query.WeeklyCompet) {
        it.createBy = localStorage.nickname,
          it.createUser = localStorage.username
      }
      let params = query
      btnLoading = true
      yield put({ type: 'updateStore', payload: { btnLoading } })
      let { success, msg, data } = yield call(addFun, { ...params })
      let flag = success.toString()
      if (flag) {
        btnLoading = false
        yield put({ type: 'updateStore', payload: { btnLoading } })
      }
      if (success) {
        message.success('提交成功')
        hashHistory.push({
          pathname: '/home/predictManage/weekReport',
          query: { tabsType: '1' }
        })
      }
    },
  },

  // 存入状态机
  reducers: {
    updateStore(preState, action) {
      return Object.assign({}, preState, action.payload)
    },
  }
}

export default tmpModule
